Ext.ns('cn.hls.web.action.dict.area');
var listView  =cn.hls.web.action.dict.listView ;
listView  = function() {
	var areaTree, store, grid, formPanel, impFormPanel, win, impWin;
	var fields = ['id',  'name', 'code', 'shortName', 'sort' ];
	var sm = new Ext.grid.CheckboxSelectionModel({
		header:' ',singleSelect : true
	});
	return {

		init : function() {
			// areaTree
			areaTree = this.createAreaTree();
			areaTree.on('click', function(node) {
				store.load({
					params : {
						'page.start' : 0,
						'page.limit' : Ext.getCmp('page').pageSize,
						'id' : node.attributes.id
					}
				});
			});
			areaTree.root.select();

			// store
			store = this.createStore();

			// 查询条件
			store.on('beforeload', function() {
					var selectModel = areaTree.getSelectionModel();
					var selectNode = selectModel.getSelectedNode();
					var id = 0;
					if (selectNode) {
						var id = selectNode.attributes.id;
					}
					this.baseParams = {
						"area.name" : Ext.getCmp('pname').getValue(),
						"area.id" : id

					};
			});

			// grid
			grid = this.createGrid();
			
			grid.on('rowdblclick', function(g, r, e) {
				 listView .editInit();
			});
			this.setGridGrog();

			// viewport
			var viewport = new Ext.Viewport({
					layout : 'border',
					items : [{
								title : '区域模块',
								iconCls : 'layout_contentIcon',
								collapsible : true,
								width : 210,
								minSize : 160,
								maxSize : 280,
								split : true,
								region : 'west',
								autoScroll : true,
								items : [areaTree]
							}, {
								region : 'center',
								layout : 'fit',
								items : [grid]
							}]
			});
			this.queryResItem();

		},
		createStore : function() {
			return new ExtStore({
				     url :'/area/list.action',
				     fields : fields
			});
		},
		
		createGrid : function() {
			return new ExtGrid({
						sm : sm,
						columnLines:true,//表格的竖线
						title : '区域模块信息表',
						iconCls : 'application_view_listIcon',
						region : 'center',
						store : store,
						// 拖动排序需配置 enableDragDrop 属性 和 dropConfig属性
						enableDragDrop : true,
						dropConfig : {
							appendOnly : true
						},
						ddGroup : "GridDD",
						ddText : "拖动后，点击操作栏，保存排序按钮！",
						renderTo : Ext.getBody(),
						sm : new Ext.grid.RowSelectionModel({singleSelect : true }),
						columns : [new Ext.grid.RowNumberer(), sm,{
									sortable : true,
									autoWidth : true,
									dataIndex : "name",
									header : "区域名称"
								},{
									sortable : true,
									dataIndex : "shortName",
									header : "区域简称",
									width : 45
								}, {
									sortable : true,
									dataIndex : "code",
									header : "区域代码",
									width : 85
								},  {
									xtype : 'uxactioncolumn',
									header : '排序',
									autoWidth : false,
									width : 30,
									items : [{
										iconCls : 'btn-up',
										tooltip : '向上（这里设定顺序后，请点击保存排序，使之生效）',
										stopSelection : false,
										scope : this,
										handler : function(grid, rowIndex,colIndex) {
											listView .onRowAction('btn-up',rowIndex);
										}
									}, {
										iconCls : 'btn-last',
										tooltip : '向下（这里设定顺序后，请点击保存排序，使之生效）',
										stopSelection : false,
										scope : this,
										handler : function(grid, rowIndex,colIndex) {
											listView .onRowAction('btn-last',rowIndex);
										}
									}]
						}],
						tbar : listView .createTbar(),
						bbar : {
							id : 'page',
							xtype : 'pageinfobar',
							pageSize : 20,
							store : store,
							pageMethod : listView .queryResItem
						}
					});
		},
		
		setGridGrog : function() {
			new Ext.dd.DropTarget(grid.container, {
						ddGroup : 'GridDD',
						copy : false,
						notifyDrop : function(dd, e, data) {
							var rows = data.selections;
							var index = dd.getDragData(e).rowIndex;
							if (typeof(index) == "undefined") {
								return;
							}
							// 确定正序还是倒序
							var mark = true;
							gridIndex = store.indexOf(rows[0]);
							if (index < gridIndex)
								mark = false;

							for (i = 0; i < rows.length; i++) {
								var rowData;
								if (mark) {
									rowData = rows[i];
								} else {
									rowData = rows[rows.length - i - 1];
								}
								if (!this.copy)
									store.remove(rowData);
								store.insert(index, rowData);
							}
							var sm = grid.getSelectionModel();
							sm.clearSelections();
							grid.getView().refresh();// 刷新序号

						}
					});

		},
		
		createTbar : function() {
			return [{
						text : '新增',
						iconCls : 'page_addIcon',
						handler : function() {
							listView .addInit();
						}
					}, '-', {
						text : '修改',
						iconCls : 'page_edit_1Icon',
						handler : function() {
							listView .editInit();
						}
					}, '-', {
						text : '删除',
						iconCls : 'page_delIcon',
						handler : function() {
							listView .deleteItem();
						}
					}, '-', {
						text : '保存排序',
						iconCls : 'save',
						handler : function() {
							var ids = '';
							var i = 0;
							grid.getStore().each(function(r) {
										++i;
										ids += r.id + ",";
							});
							if (i == 0) {
								Ext.Mytip.msg('提示', '无记录排序');
							} else if (i == 1) {
								Ext.Mytip.msg('提示', '只有一条记录，无需排序');
							} else {
								var selectModel = areaTree.getSelectionModel();
								var selectNode = selectModel.getSelectedNode();
								var parentId = selectNode.attributes.id;
								Ext.Ajax.request({
											url : cfg.cxt + '/area/sort.action',
											success : function(response) {
												var rt = Ext.decode(response.responseText);
												if (rt.success) {
													listView .refreshNode(parentId); // 刷新父节点
													Ext.Mytip.msg('提示', '排序成功！');
												} else {
													bangni.ajaxError(response);
												}
											},
											failure : bangni.ajaxError,
											params : {
												"ids" : ids
											}
										});

							}
						}
					},'-', {
						text : '导入Excel',
						iconCls : 'excel-imp-col',
						handler : function() {
							listView .impInit();
						}
					}, '->', new Ext.form.TextField({
								id : 'pname',
								emptyText : '请输入区域名称',
								enableKeyEvents : true,
								listeners : {
									specialkey : function(field, e) {
										if (e.getKey() == Ext.EventObject.ENTER) {
											listView .queryResItem();
										}
									}
								},
								width : 130
							}), {
						text : '查询',
						iconCls : 'previewIcon',
						handler : function() {
							listView .queryResItem();
						}
					}, '-', {
						text : '刷新',
						iconCls : 'arrow_refreshIcon',
						handler : function() {
							listView .queryResItem();
						}
					}];
		},
		createAreaTree : function() {
			return new Ext.tree.TreePanel({
						loader : new Ext.tree.TreeLoader({
									dataUrl : cfg.cxt + '/area/tree.action',
									listeners : {
										beforeload : function(treeLoader, node) {
											this.baseParams = {
												nodeId : node.attributes.id
											};
										},
										 loadexception : bangni.storeLoadError
									}
								}),
						root : new Ext.tree.AsyncTreeNode({
									text : '区域信息',
									expanded : true,
									id : '0'
								}),
						title : '',
						applyTo : 'areaTreeDiv',
						autoScroll : false,
						animate : false,
						useArrows : false,
						border : false
					});

		},
		queryResItem : function(v) {
			if (!v)
				v = Ext.getCmp('page').pageSize;
			store.load({
						params : {
							"page.start" : 0,
							"page.limit" : v
						}
					});
		},
		onRowAction : function(c, i) {
			var g = grid.getStore();
			switch (c) {
				case "btn-up" :
					if (i == 0) {
						Ext.Mytip.msg("操作信息", "已经为第一条!");
						return;
					}
					var h = g.getAt(i - 1);
					var f = g.getAt(i);
					g.removeAt(i);
					g.removeAt(i - 1);
					g.insert(i - 1, f);
					g.insert(i, h);
					break;
				case "btn-last" :
					if (i == g.getCount() - 1) {
						Ext.Mytip.msg("操作信息", "已经为最后一条!");
						return;
					}
					var h = g.getAt(i);
					var f = g.getAt(i + 1);
					g.removeAt(i + 1);
					g.removeAt(i);
					g.insert(i, f);
					g.insert(i + 1, h);
					break;
				default :
					break;
			}
		},

		clearForm : function(pForm) {
			var formItems = pForm.items['items'];
			for (i = 0; i < formItems.length; i++) {
				element = formItems[i];
				element.setValue('');
				element.reset(); // 避免出现红色波浪线
			};
		},
		onAddOrEditInit : function() {
			if (!formPanel) {
				formPanel = areaForm.createFormPanel();
			}
			if (!win) {
				win = areaForm.createWindow();
			}
		},
		addInit : function() {
			this.onAddOrEditInit();
			var flag = Ext.getCmp('windowmode').getValue();
			if (typeof(flag) != 'undefined') {
				formPanel.form.getEl().dom.reset();
			} else {
				this.clearForm(formPanel.getForm());
			}
			var selectModel = areaTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			Ext.getCmp('fatherId').setValue(selectNode.attributes.id);
			Ext.getCmp('areaName').setValue(selectNode.attributes.text);
			Ext.getCmp('id').setValue(0);
			Ext.getCmp('sort').setValue(1);
			win.setTitle('新增区域');
			Ext.getCmp('windowmode').setValue('add');
			win.show();
		},
		editInit : function() {
			var record = grid.getSelectionModel().getSelected();
			if (Ext.isEmpty(record)) {
				Ext.Mytip.msg('提示', '请先选择您要修改的记录');
				return;
			}
			this.onAddOrEditInit();
			formPanel.getForm().loadRecord(record);
			win.setTitle('修改区域');
			Ext.getCmp('windowmode').setValue('edit');
			var selectModel = areaTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			Ext.getCmp('fatherId').setValue(selectNode.attributes.id);
			win.show();

		},
		impInit : function(){
			if(!impFormPanel)
				impFormPanel = areaForm.createFormPanel('imp');
			if(!impWin)
				impWin = areaForm.createWindow('imp');
			
			impWin.setTitle('导入区域文件');
			impWin.show();
			
		},
		subFileForm : function(url){
			var selectModel = areaTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			var fatherId = selectNode.attributes.id;
			impFormPanel.form.submit({
						url : cfg.cxt + url,
						waitTitle : '提示',
						method : 'POST',
						waitMsg : '正在处理数据,请稍候...',
						success : function(form, action) {
							impWin.hide();
//							listView .queryResItem();
							listView .refreshNode(fatherId); // 刷新父节点
							form.reset();
							Ext.Mytip.msg('提示', '导入成功！');
						},
						failure : bangni.sumbitError
			});
		},
		subForm : function(url) {

			var mode = Ext.getCmp('windowmode').getValue();
			var selectModel = areaTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			var fatherId = selectNode.attributes.id;
			
			formPanel.form.submit({
						url : cfg.cxt + url,
						waitTitle : '提示',
						method : 'POST',
						waitMsg : '正在处理数据,请稍候...',
						success : function(form, action) {
							var r = action.result.status;
							if (r == 200){
								win.hide();
								listView.refreshNode(fatherId); //刷新父节点
								form.reset();
								if (mode == 'add')
								    Ext.Mytip.msg('提示', '新增成功！');
								else
								    Ext.Mytip.msg('提示', '修改成功！');
							}else if(r==201){//新增时存在相同的记录
								 Ext.Mytip.msg('提示', action.result.info);
							} else{
								if (mode == 'add')
								    Ext.Mytip.msg('提示', '新增失败！');
								else
								    Ext.Mytip.msg('提示', '修改失败！');
							}
						},
						failure : bangni.sumbitError
					});

		},
		deleteItem : function() {

			var record = grid.getSelectionModel().getSelected();
			if (Ext.isEmpty(record)) {
				Ext.Mytip.msg('提示', '请先选择要删除的记录！');
				return;
			}
			var selectModel = areaTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			var fatherId = selectNode.attributes.id;
			Ext.Msg.confirm('请确认',
					'<span style="color:red"><b>提示：</b>你真的要删除吗？</span>',
					function(btn, text) {
						if (btn == 'yes') {
							Ext.Ajax.request({
										url : cfg.cxt + '/area/del.action',
										success : function(response) {
											var r = Ext.decode(response.responseText);
											 if (r.success) {
												 	if(r.status == 200){
												 		 listView.refreshNode(fatherId); // 刷新父节点
														 Ext.Mytip.msg('提示','删除成功！');
													 } else {
														 Ext.Mytip.msg('提示',r.info);
													 }
												} else {
													bangni.ajaxError(response);
												}
										},
										failure : bangni.ajaxError,
										params : {
											"id" : record.data.id
										}
									});
						}
					});

		},
		getExpandedNodeIds : function(startNode){
			var expandedNodeIds=[];
	        startNode = startNode || areaTree.root;
	        var f = function(){
	            if(this.expanded){
	            	expandedNodeIds.push(this.attributes.id);
	            }
	        };
	        startNode.cascade(f);
	        return expandedNodeIds;
	},
	refreshNode : function(nodeid) {
		var expandedNodeIds=[];
		var reExpanded=function() {
			this.eachChild(function() {
				for(var i=0;i<expandedNodeIds.length;i++) {
					if(this.attributes.id==expandedNodeIds[i]) {
						if(!this.attributes.leaf)
							this.reload(reExpanded);
						break;
					}
				}
			})
		}
		
		//获取所有展开的节点id
		var node = areaTree.getNodeById(nodeid);
		/* 异步加载树在没有展开节点之前是获取不到对应节点对象的 */
		if (Ext.isEmpty(node)||Ext.isEmpty(node.parentNode)) {
			expandedNodeIds=this.getExpandedNodeIds(areaTree.root);
			areaTree.root.reload(reExpanded);
			areaTree.root.select();
			areaTree.fireEvent("click",areaTree.root);
		} else if (!Ext.isEmpty(node.parentNode)) {
			var p=node.parentNode;
			expandedNodeIds=this.getExpandedNodeIds(p);
			var expanded=node.expanded ;
			p.reload(function() {
				var newNode=areaTree.getNodeById(nodeid);
				if(newNode!=null) {
					newNode.select();
					areaTree.fireEvent("click",newNode);
				} else {
					p.select();
					areaTree.fireEvent("click",p);
				}
				reExpanded.call(this);
			});
		} 	
	 }
	}

}();

Ext.onReady(listView .init, listView );